package com.alan.libapi.api;

import com.alan.libapi.model.business.TcpJsonRequest;
import com.alan.library.allog.KLog;
import com.alibaba.fastjson.JSON;

import java.io.IOException;

/**
 * @className: ALTcpRecvNotifyClient
 * @describtion: ALTcpRecvNotifyClient
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/5/9 13:22
 */
public class ALTcpRecvNotifyClient implements IALTcpClient {

    private String hostIp;
    private int port;
    private ALTcpSocketHelper alTcpSocketHelper;
    private RecvNotifyListener recvNotifyListener;

    public ALTcpRecvNotifyClient(String hostIp, int port) {
        this.hostIp = hostIp;
        this.port = port;
        alTcpSocketHelper = new ALTcpSocketHelper(hostIp, port);
        try {
            alTcpSocketHelper.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        listenToRecvNotify();
    }

    /**
     * 监听来自客户端的请求
     */
    private void listenToRecvNotify(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                KLog.d("listenToRecvNotify()------->>>>");
                byte[] data;
                while (true) {
                    try {
                        data = alTcpSocketHelper.receiveData();
                        if (data != null && data.length > 0) {
                            synchronized (alTcpSocketHelper) {//避免keepalive导致阻塞
                                KLog.d("data.length = "+data.length);
                                handleRequest(data);
                            }
                        }else {
                            KLog.d("data == null");
                            handleRequest(-1, "客户端断开连接");
                            break;
                        }
                    } catch (Exception e) {
                        KLog.d("Exception = "+e.toString());
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }).start();
    }

    /**
     * @param requestCode
     * @param requestString
     */
    private void handleRequest(int requestCode, String requestString) {
        if(getRecvNotifyListener() != null){
            getRecvNotifyListener().onNotifyReceivecd(requestCode, requestString);
        }
    }

    /**
     * 处理客户端请求
     * @param requestData
     */
    private void handleRequest(byte[] requestData) {
        String requestString = new String(requestData);
        KLog.d("requestString = "+requestString);
        TcpJsonRequest jsonBaseRequest = JSON.parseObject(requestString, TcpJsonRequest.class);
        int id = jsonBaseRequest.getId();
        KLog.d("id = "+id);
        handleRequest(id, requestString);
    }

    /**
     * 回复客户端
     * @param msg
     */
    public void responseClient(final String msg) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (alTcpSocketHelper) {//避免keepalive导致阻塞
                        //IOS 需要读取"\r\n"作为结束标记，故在每个命令结尾加上"\r\n"
                        String finalMsg = msg + "\r\n";
                        KLog.d("responseMsg ---->>finalMsg = "+finalMsg);
                        alTcpSocketHelper.sendData(finalMsg.getBytes());
//						socketHelper.sendData(msg.getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public RecvNotifyListener getRecvNotifyListener() {
        return recvNotifyListener;
    }

    public void setRecvNotifyListener(RecvNotifyListener recvNotifyListener) {
        this.recvNotifyListener = recvNotifyListener;
    }

    @Override
    public boolean isAlive() {
        return alTcpSocketHelper.isAlive();
    }

    @Override
    public void retryConnection() throws IOException {
        alTcpSocketHelper.connect();
    }

    @Override
    public void close() throws IOException {
        alTcpSocketHelper.closeSocket();
    }
}
